// 临时引用 ，后续需要从数据库中获取
import { getComponent } from "@/components/QuestionComponents/page";
import styles from "./question.module.scss";

import PageWrapper from "../../components/PageWrapper/page";
import { getQuestionById } from "@/app/services/question";
import { Key } from "react";

export default async function Question({
  params,
}: {
  params: { question: string };
}) {
  const { question } = await params;
  const objData = await getQuestionById(question);
  console.log("page:", objData);
  //数据错误
  if (objData.errno !== 0) {
    return (
      <PageWrapper title="错误">
        <h1>错误</h1>
        <p>{objData.msg}</p>
      </PageWrapper>
    );
  }

  //已经被删除，提醒错误
  if (objData.data?.isDeleted) {
    return (
      <PageWrapper title={objData.data.title}>
        <h1>{objData.data.title}</h1>
        <p>该问卷已经被删除</p>
      </PageWrapper>
    );
  }

  //问卷未开始，提醒错误
  if (objData.data?.isPublished === false) {
    return (
      <PageWrapper title={objData.data.title}>
        <h1>{objData.data.title}</h1>
        <p>该问卷尚未发布</p>
      </PageWrapper>
    );
  }

  const componentListElem = (
    <>
      {objData.data?.componentList.map((item:any) => {
        const ComponentElement = getComponent(item);
        return (
          <div className={styles.componentWrapper} key={item.fe_id}>
            {ComponentElement}
          </div>
        );
      })}
    </>
  );

  return (
    <PageWrapper
      title={objData.data?.title || "调研问需"}
      desc={objData.data?.desc}
    >
      <form method="POST" action="/api/answer">
        <input name="questionId" defaultValue={question} type="hidden" />
        {componentListElem}
        <div className={styles.submitBtncontainer}>
          <input className={styles.input} type="submit" value="提交" />
        </div>
      </form>
    </PageWrapper>
  );
}
